Package installation

install.packages("ggmap")

library(ggplot2)
library(cowplot)
library(dplyr)
library(ggmap)

Challenge

1. Create six graphs

Load the the ggplot2 cheatsheet and the iris dataset to create six visualizations and combine them into a single figure.

Note the code for custom colors.

data(iris)
library(ggplot2)
iris_density = ggplot(iris, aes(x = Petal.Length, fill = Species)) + 
  geom_density(alpha = 0.5) + 
  theme_bw() + 
  theme(legend.position = "bottom") + 
  scale_fill_manual(values = c("orange", "yellow", "cyan"))
  
iris_density

iris_scatter = ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, 
                                color = Petal.Length)) + 
  geom_point(size = 4, alpha = 0.5) + 
  theme_bw() + 
  theme(legend.position = "left") + 
  scale_color_gradient(low = "red", high = "blue") 
  
iris_scatter

iris_box = ggplot(iris, aes(x = Species, y = Sepal.Length, 
                            fill = Species)) + 
  geom_boxplot() + 
  theme_bw() + 
  guides(fill = FALSE) + 
  scale_fill_manual(values = c("goldenrod", "salmon", "turquoise"))
  
iris_box

iris_bar = ggplot(iris, aes(x = Sepal.Width)) + 
  geom_bar(stat = "count", 
           color = "black", 
           fill = "blue") + 
  theme_bw()
  
iris_bar

iris_jitter = ggplot(iris, aes(x = Petal.Length, y = Sepal.Length, 
                               color = Species)) + 
  geom_jitter(size = 4, alpha = 0.5, 
              height = 3, width = 3) + 
  theme_bw() + 
  theme(legend.position = "top") +
  scale_color_brewer(palette = "Blues")
  
iris_jitter

iris_smooth = ggplot(iris, aes(x = Petal.Length, y = Petal.Width, 
                               color = Species)) +
  geom_point(size = 4, alpha = 0.5) + 
  geom_smooth(color = "red", lwd = 1, se = FALSE) + 
  theme_bw() + 
  theme(legend.position = "right") + 
  scale_color_hue(l = 40, c = 35)
  
iris_smooth
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

library(cowplot)
## 
## ********************************************************
## Note: As of version 1.0.0, cowplot does not change the
##   default ggplot2 theme anymore. To recover the previous
##   behavior, execute:
##   theme_set(theme_cowplot())
## ********************************************************
iris_compound = plot_grid(iris_scatter, iris_jitter, iris_smooth, 
                          iris_box, iris_density, iris_bar)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
iris_compound

ggsave(filename = "visuals/iris_compound.pdf", plot = iris_compound, 
       width = 12, height = 8, units = "in", dpi = 600)

2. Maps!

The data

For this mapping example, we will use the first 1000 rows from the Obervation.org nature dataset from the Netherlands housed at the Global Biodiversity Information Facility (GBIF) (login required; citation, citation guidelines, data user agreement.

gbif = read.csv("data/gbif_1000.csv", stringsAsFactors = TRUE, 
                sep = "\t")
head(gbif)
##       gbifID                           datasetKey
## 1 1951966751 8a863029-f435-446a-821e-275f4f641165
## 2 1951966752 8a863029-f435-446a-821e-275f4f641165
## 3 1951966753 8a863029-f435-446a-821e-275f4f641165
## 4 1951966754 8a863029-f435-446a-821e-275f4f641165
## 5 1951966755 8a863029-f435-446a-821e-275f4f641165
## 6 1951966756 8a863029-f435-446a-821e-275f4f641165
##                                   occurrenceID  kingdom     phylum   class
## 1 https://observation.org/observation/89083645 Animalia Arthropoda Insecta
## 2 https://observation.org/observation/89083599 Animalia   Chordata    Aves
## 3 https://observation.org/observation/89083416 Animalia   Chordata    Aves
## 4 https://observation.org/observation/89083564 Animalia   Chordata    Aves
## 5 https://observation.org/observation/89083635 Animalia   Chordata    Aves
## 6 https://observation.org/observation/89083429 Animalia   Chordata    Aves
##             order       family   genus          species
## 1     Lepidoptera  Nymphalidae  Aglais        Aglais io
## 2   Passeriformes     Corvidae Coloeus Coloeus monedula
## 3 Accipitriformes Accipitridae  Circus Circus macrourus
## 4   Passeriformes     Turdidae  Turdus    Turdus merula
## 5   Passeriformes Fringillidae Chloris  Chloris chloris
## 6 Charadriiformes      Alcidae    Uria       Uria aalge
##   infraspecificEpithet taxonRank                      scientificName
## 1                        SPECIES          Aglais io (Linnaeus, 1758)
## 2                        SPECIES   Coloeus monedula (Linnaeus, 1758)
## 3                        SPECIES Circus macrourus (S.G.Gmelin, 1770)
## 4                        SPECIES        Turdus merula Linnaeus, 1758
## 5                        SPECIES    Chloris chloris (Linnaeus, 1758)
## 6                        SPECIES      Uria aalge (Pontoppidan, 1763)
##   verbatimScientificName verbatimScientificNameAuthorship countryCode
## 1              Aglais io                               NA          NL
## 2       Coloeus monedula                               NA          NL
## 3       Circus macrourus                               NA          NL
## 4          Turdus merula                               NA          NL
## 5        Chloris chloris                               NA          NL
## 6             Uria aalge                               NA          NL
##                                 locality stateProvince occurrenceStatus
## 1                             Veenendaal       Utrecht               NA
## 2                   Colijnsplaat - Haven       Zeeland               NA
## 3 Texel - Eierland - Oorsprongweg - west Noord-Holland               NA
## 4                             Koudekerke       Zeeland               NA
## 5              Vlieland - Waterzuivering     Friesland               NA
## 6                    IJmuiden - Zuidpier Noord-Holland               NA
##   individualCount                     publishingOrgKey decimalLatitude
## 1               1 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           52.00
## 2               6 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           51.60
## 3               1 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           53.10
## 4               1 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           51.45
## 5               1 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           53.25
## 6               1 c8d737e0-2ff8-42e8-b8fc-6b805d26fc5f           52.45
##   decimalLongitude coordinateUncertaintyInMeters coordinatePrecision
## 1             5.55                          5000                  NA
## 2             3.85                          5000                  NA
## 3             4.80                          5000                  NA
## 4             3.55                          5000                  NA
## 5             5.05                          5000                  NA
## 6             4.50                          5000                  NA
##   elevation elevationAccuracy depth depthAccuracy            eventDate day
## 1        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
## 2        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
## 3        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
## 4        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
## 5        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
## 6        NA                NA    NA            NA 2014-10-10T00:00:00Z  10
##   month year taxonKey speciesKey     basisOfRecord institutionCode
## 1    10 2014  4535827    4535827 HUMAN_OBSERVATION              NA
## 2    10 2014  6100954    6100954 HUMAN_OBSERVATION              NA
## 3    10 2014  2480491    2480491 HUMAN_OBSERVATION              NA
## 4    10 2014  2490719    2490719 HUMAN_OBSERVATION              NA
## 5    10 2014  5845582    5845582 HUMAN_OBSERVATION              NA
## 6    10 2014  2481342    2481342 HUMAN_OBSERVATION              NA
##   collectionCode catalogNumber recordNumber identifiedBy dateIdentified
## 1   Observations  OBS.89083645           NA           NA             NA
## 2   Observations  OBS.89083599           NA           NA             NA
## 3   Observations  OBS.89083416           NA           NA             NA
## 4   Observations  OBS.89083564           NA           NA             NA
## 5   Observations  OBS.89083635           NA           NA             NA
## 6   Observations  OBS.89083429           NA           NA             NA
##        license               rightsHolder recordedBy typeStatus
## 1 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
## 2 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
## 3 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
## 4 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
## 5 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
## 6 CC_BY_NC_4_0 Stichting Natuurinformatie         NA         NA
##   establishmentMeans          lastInterpreted mediaType issue
## 1                 NA 2019-09-20T15:16:10.208Z        NA      
## 2                 NA 2019-09-20T18:27:13.067Z        NA      
## 3                 NA 2019-09-20T18:04:30.994Z        NA      
## 4                 NA 2019-09-21T02:02:55.492Z        NA      
## 5                 NA 2019-09-20T18:08:17.611Z        NA      
## 6                 NA 2019-09-21T00:22:32.721Z        NA
Connecting to the Google Maps Static API

If you want to add your data to Google Maps, you must first 1) enable the Maps Static API and 2) enable billing by entering your credit card information. Don’t worry though, Google gives you a bunch of free credits and will not charge you without your permission.

  1. Visit https://cloud.google.com/

  2. Click “Go to console”

  3. Login with a gmail account and click “Create Project” and enter your information

  4. Click the hamburger and then “APIs and Services”

  5. Click “+ Enable APIs and Services” and search for “Maps Static API”, then click “Enable”

  6. Click the hamburger and then “APIs and Services”

  7. Click “Credentials” then “Create Credentials” then “API key”

  8. You should see a popup window that says “API key created” - click “Restrict key”, then select “Restrict key”, click the dropdown menu and select “Static Maps API” and then save

  9. In the searchbar, type “billing” and select “Billing”, click “Manage Billing Accounts” and then “Add Billing Account”. Enter your information and select “Save and enable billing”

  10. Copy your API key into the below code:

## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.
## 
## Attaching package: 'ggmap'
## The following object is masked from 'package:cowplot':
## 
##     theme_nothing
ggmap::register_google(key = "YOUR API KEY HERE") 
# choose the lat/lon from the first row in the gbif dataset as the center point
# you might want to find something more central! 
netherlands = ggmap(get_googlemap(center = c(lon = 5.55, lat = 52.00),
                                  zoom = 7, scale = 2,
                                  maptype = "terrain",
                                  color = "color"))
## Source : https://maps.googleapis.com/maps/api/staticmap?center=52,5.55&zoom=7&size=640x640&scale=2&maptype=terrain&key=xxx
netherlands

ggsave(filename = "visuals/netherlands.pdf", plot = netherlands, 
       width = 12, height = 8, units = "in", dpi = 600)

If this does not work, you might need the GitHub version of ggmap

devtools::install_github("dkahle/ggmap")
library(ggmap)

Now, we can plot the rest of the data on the Google Map

gbif_center_point = c(lon = 5.55, lat = 52.00)

gbif_map = get_map(gbif_center_point, zoom = 7) 
## Source : https://maps.googleapis.com/maps/api/staticmap?center=52,5.55&zoom=7&size=640x640&scale=2&maptype=terrain&language=en-EN&key=xxx
# Country overlay
netherlands_data = ggmap(gbif_map) + 
  geom_point(data = gbif, alpha = 0.5, 
             aes(x = decimalLongitude, y = decimalLatitude, 
                 col = kingdom)) 

netherlands_data

ggsave(filename = "visuals/netherlands_data.pdf", plot = netherlands_data, 
       width = 12, height = 8, units = "in", dpi = 600)

# Facet by province
netherlands_facet = ggmap(gbif_map) + 
  geom_point(data = gbif, alpha = 0.5, 
             aes(x = decimalLongitude, y = decimalLatitude, 
                 col = kingdom)) + 
  ggtitle("Observation variation by Netherlands province") + 
  facet_wrap(~stateProvince)

netherlands_facet

ggsave(filename = "visuals/netherlands_facet.pdf", plot = netherlands_facet, 
       width = 12, height = 8, units = "in", dpi = 600)

Be sure to click “Shut Down” on your Google Cloud project when you are done so that it does not run in perpetuity :)